<template>
  <div>
    <uploader
      ref="uploader"
      class="uploader-example"
      :options="options"
      :autoStart="autoStart"
      @file-added="onFileAdded"
      @file-success="onFileSuccess"
      @file-progress="onFileProgress"
      @file-error="onFileError"
    >
      <uploader-unsupport></uploader-unsupport>
      <uploader-drop>
        <span>附件类型：文档</span>
        <uploader-btn :single="true">
          <i class="el-icon-circle-plus"></i>
          点击上传
        </uploader-btn>
        <span>未选择文件</span>
      </uploader-drop>
      <uploader-list>
        <template slot-scope="props">
          <ul>
            <li v-for="(file, index) in fileList" :key="index">
              <div class="uploader-file">
                <p class="img">
                  <img
                    class="el-upload-list__item-thumbnail"
                    src="../assets/images/file.png"
                    alt=""
                  />
                </p>
                <div class="preview">
                  <p class="fileNameBox">
                    <span class="fileIcon"></span>
                    {{ file.attach_name }}
                  </p>
                  <div class="filebox">
                    <p class="fileInfoBox">
                      <span class="fileInfoItem">
                        文件大小：{{
                          (file.attach_size / 1024 / 1024).toFixed(2) + "M"
                        }}
                      </span>
                      <span class="fileInfoItem">
                        {{ file.type === "1" ? "文档文件" : "视频文件" }}
                      </span>
                    </p>
                  </div>
                  <div class="preview-btn">
                    <div class="del" @click="fileRemove(file, index)">
                      <img src="../assets/images/del.png" alt="" />
                    </div>
                  </div>
                </div>
              </div>
            </li>
            <li
              v-for="(file, index) in props.fileList"
              :key="file.id"
              class="liItem"
            >
              <uploader-file
                :file="file"
                :list="true"
                ref="uploaderFile"
                :pauseFlag="pauseFlag"
              >
                <template slot-scope="props">
                  <p class="img">
                    <img
                      class="el-upload-list__item-thumbnail"
                      src="../assets/images/file.png"
                      alt=""
                    />
                  </p>
                  <div class="preview">
                    <p class="fileNameBox">
                      <span class="fileIcon"></span>
                      {{ file.name }}
                    </p>
                    <div class="filebox">
                      <p class="fileInfoBox">
                        <span class="fileInfoItem"
                          >速度：{{
                            pauseFlag ? 0 : props.formatedAverageSpeed
                          }}</span
                        >
                        <span class="fileInfoItem"
                          >已上传：{{
                            (
                              parseFloat(props.formatedSize) * props.progress
                            ).toFixed(1)
                          }}/{{ props.formatedSize }}</span
                        >
                        <span class="fileInfoItem">{{
                          fileStatusText(props.status)
                        }}</span>
                      </p>
                    </div>
                    <div class="fileProgressBox">
                      <el-progress
                        class="progressLength"
                        :percentage="
                          parseInt(
                            props.progress.toFixed(2) * 100 - 1 < 0
                              ? 0
                              : props.progress.toFixed(2) * 100
                          )
                        "
                      ></el-progress>
                    </div>
                    <div class="preview-btn">
                      <div class="del" @click="fileRemove(file, index)">
                        <img src="../assets/images/del.png" alt="" />
                      </div>
                    </div>
                  </div>
                </template>
              </uploader-file>
            </li>
          </ul>
        </template>
      </uploader-list>
    </uploader>
    <template v-if="dialogVisible">
      <el-dialog
        v-dialogDrag
        title="预览"
        :visible.sync="dialogVisible"
        width="80%"
        custom-class="filePreview"
        :fullscreen="FullScreen"
        :before-close="handleClose"
      >
        <!-- <div class="main">
        <i class="el-icon-rank" @click="onFullScreen"></i>
          <p class="page-number">{{currentPage}} / {{pageCount}}</p>
        <span @click="prePage" class="el-icon-arrow-left"></span>
        <span @click="nextPage" class="el-icon-arrow-right"></span>
        <pdf
          :page="currentPage"
          @num-pages="pageCount = $event"
          @loaded="loadPdfHandler"
          :src="'http://sapi.ps.cqooc.com/unit/attach/playurl?attach_id=8' + '&token='+token"
        >
        </pdf>
      </div> -->
        <iframe
          :src="currentFilePath"
          frameborder="0"
          style="width: 100%; height: 100%"
        ></iframe>
      </el-dialog>
    </template>
  </div>
</template>
<script type="javasciprt">
import _ from "lodash";
import pdf from "vue-pdf";
import axios from "axios";
import SparkMD5 from "spark-md5";

export default {
  name: "File",
  data() {
    var that = this;
    return {
      options: {
        target: "http://sapi.ps.cqooc.com/unit/attach/upload2",
        query: {
          token: sessionStorage.getItem("token"),
        },
        testChunks: true,
        parseTimeRemaining: function (timeRemaining, parsedTimeRemaining) {
          return parsedTimeRemaining
            .replace(/\syears?/, "年")
            .replace(/\days?/, "天")
            .replace(/\shours?/, "小时")
            .replace(/\sminutes?/, "分钟")
            .replace(/\sseconds?/, "秒");
        },
        checkChunkUploadedByResponse: function (chunk, message) {
          const obj = JSON.parse(message);
          if (obj.isexist) {
            that.statusTextMap.success = "秒传文件";
            return true;
          }
        },
      },
      pauseFlag: "",
      fileArray: [],
      autoStart: false,
      statusTextMap: {
        success: "上传成功",
        error: "上传出错了",
        uploading: "上传中...",
        paused: "暂停",
        waiting: "等待中...",
        cmd5: "计算md5...",
      },
      fileData: [],
      // 获取文件已经上传列表
      fileList: [],
      FileLimit: {
        FileMaxSize: 10,
        FileFormat: ["pdf", "doc", "docx", "xls", "xlsx"],
        // 数量
        limit: 0,
        FileUnit: "M",
      },
      dialogVisible: false,
      loadingTask: "",
      currentPage: 1,
      pageCount: 0,
      token: sessionStorage.getItem("token"),
      FullScreen: false,
      currentFilePath: "",
      fileStatusText: (status, response) => {
        return this.statusTextMap[status];
      },
    };
  },
  props: {
    attachDoc: String,
    attachDocNum: String,
    attachDocSize: String,
    fileListData: Array,
  },
  components: {
    pdf,
  },
  watch: {
    attachDoc: function (newVal, oldVal) {
      if (newVal) {
        this.attachDocFun();
      }
    },
    attachDocNum: function (newVal, oldVal) {
      if (newVal) {
        this.attachDocNumFun();
      }
    },
    attachDocSize: function (newVal, oldVal) {
      if (newVal) {
        this.attachDocSizeFun();
      }
    },
    fileListData: function (newVal, oldVal) {
      if (newVal) {
        this.attachFileListData();
      }
    },
  },
  methods: {
    attachDocFun() {
      this.FileLimit.FileFormat = this.attachDoc.split(",");
    },
    attachDocNumFun() {
      this.FileLimit.limit = Number(this.attachDocNum);
    },
    attachDocSizeFun() {
      this.FileLimit.FileMaxSize = this.attachDocSize;
    },
    attachFileListData() {
      this.fileList = this.fileListData;
      this.fileList.forEach((item) => {
        const obj = {};
        obj["attach_name"] = item.attach_name;
        obj["attach_url"] = item.attach_url;
        obj["attach_size"] = item.attach_size;
        obj["type"] = "1";
        this.fileData.push(obj);
      });
    },
    onFileSuccess(rootFile, file, response, chunk) {
      response = JSON.parse(response);
      const obj = {};
      obj["attach_name"] = file.name;
      obj["attach_url"] = response.url;
      obj["attach_size"] = file.size;
      obj["type"] = "1";
      this.fileData.push(obj);
      this.$emit("attachFile", this.fileData);
      var datatmp = new FormData();
      datatmp.append("token", this.token);
      datatmp.append("filename", file.name);
      datatmp.append("identifier", file.uniqueIdentifier);
      datatmp.append("totalSize", file.size);
      datatmp.append("totalChunks", chunk.offset + 1);
      console.log(datatmp);
      if (response.merge) {
        axios
          .post(
            "http://sapi.ps.cqooc.com/unit/attach/upload2?action=merge",
            datatmp
          )
          .then((res) => {
            console.warn("onFIleSuccess res", res);
            if (res.code === 0) {
              console.warn("onFileSuccess 上传成功");
            } else {
              console.warn("onFileSuccess", res.message);
            }
          })
          .catch(function (error) {
            console.log(error);
          });
      } else {
        return;
      }
    },
    onFileAdded(file) {
      const limit = this.FileLimit.limit;
      this.fileArray = this.fileArray.concat(this.fileList);
      if (this.fileArray.length >= limit && limit !== 0) {
        this.$message.error(`只允许上传${limit}个`);
        file.ignored = true;
        file.cancel();
        return false;
      } else {
        this.fileArray.push(file);
        const fileExtension = file.getExtension();
        var FileLimit = this.FileLimit;
        const isFormat = this.checkExtensions(
          fileExtension,
          FileLimit.FileFormat
        );
        if (!isFormat) {
          file.ignored = true;
          file.cancel();
          return false;
        }
        const isSize = this.checkSize(file.size);
        if (!isSize) {
          file.ignored = true;
          file.cancel();
          return false;
        } else {
          this.panelShow = true;
          this.show_filename = false;
          this.computeMD5(file);
        }
      }
    },
    checkSize(fileSize) {
      var FileLimit = this.FileLimit;
      var isSize = fileSize / 1024 / 1024 < FileLimit.FileMaxSize;
      console.log(isSize);
      if (!isSize) {
        this.$message.warning(
          " 文件大小不能大于" + FileLimit.FileMaxSize + FileLimit.FileUnit + "!"
        );
        return false;
      }
      return true;
    },
    checkExtensions(extension, extensions) {
      if (!_.includes(extensions, extension)) {
        this.$message.warning(`请上传${extensions.join(",")}的格式!`);
        return false;
      }
      return true;
    },
    handlePictureCardPreview(file, fileList) {
      this.dialogVisible = true;
      // let reader = new FileReader()
      // reader.readAsDataURL(file.file)
      // reader.onload=()=>  {
      //   this.currentFilePath = reader.result;
      //   console.warn('reader', reader.result)
      // }

      // this.currentFilePath = file.relativePath;
    },
    handleClose() {
      this.dialogVisible = false;
    },
    onFileError(rootFile, file, response, chunk) {},
    onFileProgress(rootFile, file, chunk) {},
    computeMD5(file) {
      const blobSlice =
        File.prototype.slice ||
        File.prototype.mozSlice ||
        File.prototype.webkitSlice;
      var chunkSize = 1048576;
      var chunks = Math.ceil(file.size / chunkSize);
      var currentChunk = 0;
      var spark = new SparkMD5.ArrayBuffer();
      var fileReader = new FileReader();
      var time = new Date().getTime();
      file.cmd5 = true;
      fileReader.onload = (e) => {
        spark.append(e.target.result);
        currentChunk++;
        if (currentChunk < chunks) {
          console.log(
            `第${currentChunk}分片解析完成, 开始第${
              currentChunk + 1
            } / ${chunks}分片解析`
          );
          loadNext();
        } else {
          console.log("finished loading");
          const md5 = spark.end();
          console.log(
            `MD5计算完成：${file.name} \nMD5：${md5} \n分片：${chunks} 大小:${
              file.size
            } 用时：${new Date().getTime() - time} ms`
          );
          spark.destroy();
          file.uniqueIdentifier = md5;
          file.cmd5 = false;
          file.resume();
        }
      };
      fileReader.onerror = () => {
        console.warn("oops, something went wrong.");
        file.cancel();
      };
      const loadNext = () => {
        var start = currentChunk * chunkSize;
        var end =
          start + chunkSize >= file.size ? file.size : start + chunkSize;
        fileReader.readAsArrayBuffer(blobSlice.call(file.file, start, end));
      };
      loadNext();
    },
    fileRemove(file, index) {
      if (this.fileList.length != 0) {
        this.fileList.splice(index, 1);
      } else {
        file.cancel();
      }
      const newList = [];
      this.fileArray.forEach((item, idx) => {
        if (idx !== index) {
          newList.push(item);
        } else {
          newList.splice(idx, 1);
        }
      });
      const newDataList = [];
      // console.log(this.fileData);
      this.fileData.forEach((item, idx) => {
        if (idx !== index) {
          newDataList.push(item);
        } else {
          newDataList.splice(idx, 1);
        }
      });
      this.fileArray = newList;
      this.fileData = newDataList;
      this.$emit("attachFile", newDataList);
    },
    // 预览
    prePage() {
      if (this.currentPage <= 1) return;
      this.currentPage -= 1;
    },
    nextPage() {
      if (this.currentPage >= this.pageCount) return;
      this.currentPage += 1;
    },
    loadPdfHandler(e) {
      this.currentPage = 1; // 加载的时候先加载第一页
    },
    onFullScreen() {
      this.FullScreen = !this.FullScreen;
    },
  },
  created() {},
  mounted() {
    // this.$nextTick(() => {
    //   this.uploaderInstance = this.$refs.uploader.uploader;
    // });
  },
};
</script>
<style lang='scss' scoped>
.uploader-drop {
  border: none;
  background-color: transparent;
  padding: 0;
  & > span:first-of-type {
    margin-right: 10px;
  }
  span {
    font-size: 16px;
  }
}
.uploader-example .uploader-btn {
  margin-right: 4px;
}
.uploader-example .uploader-list {
  max-height: 440px;
  width: 60%;
  overflow: auto;
  overflow-x: hidden;
  overflow-y: auto;
}
.uploader-file {
  position: relative;
  display: flex;
  align-items: center;
  height: auto;
  margin-top: 10px;
  border: none;
  width: 100%;
  padding: 10px 22px;
  background-color: #f4f7fc;
  border-radius: 5px;
}
.uploader-btn {
  padding: 5px 10px 5px 10px;
  margin-right: 10px;
  background-color: #e5eefe;
  border: solid 1px #c8e3fe;
  color: #2197fd;
  border-radius: 5px;
  font-size: 14px;
  letter-spacing: 1px;
  &:hover {
    background-color: #e5eefe;
    border: solid 1px #c8e3fe;
  }
}
.el-progress {
  width: 95%;
  display: flex;
  align-items: center;
}
.img {
  font-size: 0;
  width: 30px;
  height: 30px;
  margin-right: 30px;
  img {
    display: block;
  }
}
.preview {
  width: 85%;
}
.fileProgressBox {
  display: flex;
  align-items: center;
}
.filebox {
  display: flex;
}
.fileNameBox {
  display: flex;
  width: 100%;
  line-height: 20px;
  font-size: 16px;
}
.fileInfoBox {
  width: 100%;
  line-height: 20px;
  display: flex;
  flex-wrap: wrap;
}
.fileInfoItem {
  margin-right: 20px;
  line-height: 28px;
  font-size: 16px;
}
.preview-btn {
  position: absolute;
  right: 3%;
  top: 50%;
  height: 25px;
  transform: translateY(-50%);
  width: 3%;
  font-size: 0;
  .del {
    width: 80%;
    height: 80%;
    float: left;
  }
}
/deep/.el-dialog__body {
  padding: 10px 20px 20px !important;
}
.main {
  position: relative;
  .page-number {
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    color: #000;
    z-index: 1;
  }
  .el-icon-arrow-left,
  .el-icon-arrow-right {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    font-size: 30px;
    color: #000;
    z-index: 1;
  }
  .el-icon-arrow-left {
    left: 10px;
  }
  .el-icon-arrow-right {
    right: 10px;
  }
}
/deep/.filePreview {
  height: 100%;
  i {
    font-size: 20px;
  }
  /deep/.el-dialog__header {
    padding: 0.25rem 0.25rem 0.125rem;
  }
  /deep/.el-dialog__body {
    padding-top: 0 !important;
    height: 90%;
  }
  /deep/.el-icon-rank {
    position: absolute;
    right: 3%;
    top: 0.28rem;
    font-size: 16px !important;
    color: #909399;
  }
}
</style>
